import mysql.connector
from mysql.connector import Error

def download_blob_to_file(host, user, password, database, table, blob_column, output_path):
    try:
        # 连接数据库
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        cursor = connection.cursor()

        # 查询BLOB数据
        query = f"SELECT {blob_column} FROM {table} "
        cursor.execute(query)
        blob_data1 = cursor.fetchone()
        for blob_data in blob_data1:
            # 保存为文件
            with open(output_path, 'wb') as file:
                file.write(blob_data)
            print(f"文件已保存至: {output_path}")

    except Error as e:
        print(f"数据库错误: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

# 调用示例
download_blob_to_file(
    host="127.0.0.1",
    user="root",
    password="123456",
    database="scrapy",
    table="piano_scores",
    blob_column="image_data",
    # id_value=1,  # 根据实际ID修改
    output_path="downloaded_image1.jpg"
)
